package com.taotao.manage.service.impl;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.github.pagehelper.PageHelper;
import com.taotao.manage.pojo.BasePojo;
import com.taotao.manage.service.BaseService;

import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

public abstract class BaseServiceImpl<T extends BasePojo> implements BaseService<T> {

	@Autowired // 如果使用了spring 4.x及以上版本,可以使用泛型依赖注入;可以注入继承了Mapper<T>接口的子类,,根据T找到相应的mapper
	private Mapper<T> mapper;

	private Class<T> clazz;

	public BaseServiceImpl() {
		// pt --> BaseServiceImpl<User>; this表示当前被实例化的对象,如UserServiceImpl
		ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();

		// clazz ---> User类
		clazz = (Class<T>) pt.getActualTypeArguments()[0];
	}

	@Override
	public T queryById(Serializable id) {
		return mapper.selectByPrimaryKey(id);
	}

	@Override
	public List<T> queryAll() {
		return mapper.selectAll();
	}

	@Override
	public Integer queryCountByWhere(T t) {
		return mapper.selectCount(t);
	}

	@Override
	public List<T> queryListByWhere(T t) {
		return mapper.select(t);
	}

	@Override
	public List<T> queryListByPage(Integer page, Integer rows) {
		// 设置分页
		PageHelper.startPage(page, rows);
		return mapper.select(null);
	}

	@Override
	public void saveSelective(T t) {
		if (t.getCreated() == null) {
			t.setCreated(new Date());
		} 
		if(t.getUpdated()==null) {
			t.setUpdated(t.getCreated());
		}
		mapper.insertSelective(t);
	}

	@Override
	public void updateSelective(T t) {
		if (t.getUpdated() == null) {
			t.setUpdated(new Date());
		}
		mapper.updateByPrimaryKeySelective(t);
	}

	@Override
	public void deleteById(Serializable id) {
		mapper.deleteByPrimaryKey(id);
	}

	@Override
	public void deleteByIds(Serializable[] ids) {
		// 设置删除的条件
		Example example = new Example(clazz);
		Criteria criteria = example.createCriteria();
		// 类似构建id in(1,2,3)
		criteria.andIn("id", Arrays.asList(ids));

		// 执行批量删除
		mapper.deleteByExample(example);
	}

}
